<template>
  <div class="tool-borrow-add">
    <section class="page-hero">
      <div class="hero-content">
        <div>
          <p class="hero-pretitle">工具管理 · 工具领用</p>
          <h1>{{ form.id ? "编辑工具领用单" : "新建工具领用单" }}</h1>
          <p class="hero-desc">
            管理领用编号、领用人及明细，确保每一件工具都有迹可循。
          </p>
        </div>
        <div class="hero-actions">
          <el-tag
            class="hero-tag"
            :type="form.autoNo ? 'success' : 'info'"
            effect="dark"
          >
            自动编号{{ form.autoNo ? "已启用" : "未启用" }}
          </el-tag>
          <el-button text class="hero-back" @click="handleCancel">
            返回列表
          </el-button>
        </div>
      </div>
      <div class="hero-stats">
        <div class="stat-card">
          <span class="stat-label">当前编号</span>
          <strong class="stat-value">{{ form.borrowNo || "尚未生成" }}</strong>
          <small class="stat-tip">可由系统自动生成</small>
        </div>
        <div class="stat-card">
          <span class="stat-label">领用时间</span>
          <strong class="stat-value">{{
            form.borrowTime ? form.borrowTime.slice(0, 10) : "未选择"
          }}</strong>
          <small class="stat-tip">建议与计划时间保持一致</small>
        </div>
        <div class="stat-card">
          <span class="stat-label">明细条目</span>
          <strong class="stat-value">{{ form.details.length }}</strong>
          <small class="stat-tip">已选工具总数 {{ detailTotal }}</small>
        </div>
        <div class="stat-card">
          <span class="stat-label">领用人</span>
          <strong class="stat-value">{{
            form.borrowerName || "待选择"
          }}</strong>
          <small class="stat-tip">{{
            form.borrowDeptName || "尚未关联部门"
          }}</small>
        </div>
      </div>
    </section>

    <el-card shadow="never" class="section-card base-card">
      <template #header>
        <div class="card-header">
          <div>
            <h3>基础信息</h3>
            <p>填写领用编号、时间及人员信息，建议先确认领用权限。</p>
          </div>
          <div class="card-header-actions">
            <span class="card-hint">系统自动编号</span>
            <el-switch v-model="form.autoNo" @change="handleAutoNoChange" />
            <el-button
              text
              size="small"
              :disabled="!form.autoNo"
              @click="generateBorrowNo"
            >
              重新生成
            </el-button>
          </div>
        </div>
      </template>
      <el-form
        :model="form"
        label-width="96px"
        class="base-form"
        label-position="top"
      >
        <el-row :gutter="16">
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="领用编号">
              <el-input
                v-model="form.borrowNo"
                :disabled="form.autoNo"
                placeholder="请输入或由系统生成"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="领用名称" required>
              <el-input
                v-model="form.borrowName"
                placeholder="例如：生产线A更换工具"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="领用时间">
              <el-date-picker
                v-model="form.borrowTime"
                type="date"
                value-format="YYYY-MM-DDTHH:mm:ss"
                placeholder="请选择领用日期"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="领用人">
              <div class="borrower-input">
                <el-input
                  v-model="form.borrowerName"
                  placeholder="请选择领用人"
                  disabled
                />
                <el-tooltip content="选择领用人" placement="top">
                  <el-button
                    class="borrower-picker-btn"
                    circle
                    type="primary"
                    :loading="userLoading"
                    @click="openUserDialog"
                  >
                    <el-icon><User /></el-icon>
                  </el-button>
                </el-tooltip>
              </div>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="领用部门">
              <el-input
                v-model="form.borrowDeptName"
                placeholder="请选择领用人后自动带入"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="领用类型">
              <el-select
                v-model="form.borrowTypeId"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :value="item.id"
                  :label="item.borrowTypeName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="补充说明，如借出原因、工单等信息"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="section-card detail-card">
      <template #header>
        <div class="card-header">
          <div>
            <h3>领用明细</h3>
            <p>记录每一件领用工具及状态，支持批量增删。</p>
          </div>
          <div class="card-header-actions">
            <el-tag effect="plain" size="small"
              >共 {{ form.details.length }} 条，{{ detailTotal }} 件工具</el-tag
            >
          </div>
        </div>
      </template>
      <div class="detail-toolbar">
        <div class="toolbar-left">
          <el-button type="primary" size="small" @click="handleAddDetail">
            添加明细
          </el-button>
          <el-button size="small" @click="handleRemoveDetail"
            >移除选中</el-button
          >
        </div>
        <el-alert
          title="请优先选择工装夹具，再补充库位和状态。"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
      <el-table
        :data="form.details"
        border
        stripe
        class="detail-table"
        empty-text="暂未添加明细"
        @selection-change="handleDetailSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column label="工装夹具" min-width="200">
          <template #default="{ row }">
            <el-select
              v-model="row.toolFixtureId"
              placeholder="选择工装夹具"
              filterable
              clearable
              @change="handleFixtureChange(row, $event)"
            >
              <el-option
                v-for="item in fixtureOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="领用数量" width="120" align="center">
          <template #default="{ row }">
            <el-input-number v-model="row.borrowCount" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="库位" min-width="180">
          <template #default="{ row }">
            <el-select
              v-model="row.storageLocationId"
              placeholder="选择库位"
              filterable
              clearable
              @change="handleSeatChange(row, $event)"
            >
              <el-option
                v-for="item in seatOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="工具状态" min-width="160">
          <template #default="{ row }">
            <el-select
              v-model="row.toolStatusWhenBorrow"
              placeholder="选择状态"
              clearable
            >
              <el-option
                v-for="item in toolStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="200">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="备注信息" clearable />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110" align="center" fixed="right">
          <template #default="{ $index }">
            <el-button
              type="danger"
              link
              size="small"
              @click="removeDetailAt($index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="detail-summary">
        <span>领用总数：{{ detailTotal }}</span>
        <span>最后更新时间：{{ new Date().toLocaleString() }}</span>
      </div>
    </el-card>

    <div class="page-actions">
      <div class="actions-hint">
        <p>确认信息无误后再提交，系统将立即生效。</p>
      </div>
      <div class="actions-buttons">
        <el-button @click="handleCancel">关闭</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">
          确认提交
        </el-button>
      </div>
    </div>
    <el-dialog v-model="userDialogVisible" title="选择领用人" width="680">
      <div class="manager-search">
        <el-input
          v-model="userKeyword"
          placeholder="请输入姓名/工号/部门关键字"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <el-table :data="filteredUsers" v-loading="userLoading" height="360px">
        <el-table-column prop="username" label="姓名" width="140" />
        <el-table-column prop="usernumber" label="工号" width="140" />
        <el-table-column prop="organname" label="部门" />
        <el-table-column prop="phone" label="联系方式" width="140" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleUserPick(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { Search, User } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import https from "@/Http/http";

// API 响应类型定义
interface ApiResult<T> {
  code: number;
  msg?: string;
  data: T;
}

interface ApiPageing<T> {
  code: number;
  msg?: string;
  data: T[];
  totalCount?: number;
  pageCount?: number;
}

// 用户选项类型
interface UserOption {
  label: string;
  value: number;
}

// 用户 DTO
interface UserDto {
  id: number;
  username: string;
  usernumber?: string;
  accountname?: string;
  usersex?: string;
  phone?: string;
  emails?: string;
  status?: number;
  roleid?: number;
  rolename?: string;
  organid?: number;
  organname?: string;
  jobid?: number;
  jobname?: string;
}

// 组织DTO类型（支持Id和id两种属性名，因为JSON序列化可能使用camelCase）
interface OrganDto {
  Id?: number;
  id?: number; // JSON序列化后可能是小写
  organname: string;
  organnumber?: string;
  prgantype?: string;
  prgannum?: string;
  prganfunctionary?: string;
  prgandesc?: string;
  prganparent?: number;
}

// 部门选项类型
interface DepartmentOption {
  label: string;
  value: number;
}

// 领用类型选项类型
interface BorrowTypeOption {
  id: number | null;
  borrowTypeName: string;
}

// 明细行类型
interface FixtureOption {
  label: string;
  value: number;
  seatId?: number;
  seatName?: string;
}

interface SelectOption {
  label: string;
  value: number;
}

interface DetailRow {
  id?: number;
  toolFixtureId: number | null;
  toolFixtureName?: string;
  borrowCount: number | string;
  storageLocationId: number | null;
  storageLocationName?: string;
  toolStatusWhenBorrow: number | null;
  remark?: string;
}

// 表单数据类型
interface ToolBorrowForm {
  id: number;
  borrowNo: string;
  autoNo: boolean;
  borrowName: string;
  borrowerId: number | null;
  borrowerName: string;
  borrowDept: number | null;
  borrowDeptName: string;
  borrowTypeId: number | null;
  borrowTime: string;
  borrowStatus: number;
  remark: string;
  details: DetailRow[];
}

// 工具领用详情 DTO
interface ToolBorrowHeaderDetailDto {
  id: number;
  borrowNo: string;
  borrowName: string;
  borrowerId: number;
  borrowerName?: string;
  borrowDept: number | string | null;
  borrowDeptName?: string;
  borrowTypeId: number;
  borrowTypeName?: string;
  borrowTime: string | Date;
  borrowStatus: number;
  remark?: string;
  details: ToolBorrowDetailItemDto[];
}

// 工具领用明细项 DTO
interface ToolBorrowDetailItemDto {
  id: number;
  borrowOrderId?: number;
  toolFixtureId: number;
  toolFixtureName?: string;
  borrowCount: number;
  storageLocationId: number;
  storageLocationName?: string;
  toolStatusWhenBorrow: number;
  remark?: string;
}

interface WorkFixtureDto {
  id: number;
  work_fixturename: string;
  work_fixtureseatid?: number;
  work_fixtureseatname?: string;
}

interface WorkFixtureSeatDto {
  id: number;
  work_fixtureseatname: string;
}

// 新增请求载荷类型
interface AddToolBorrowPayload {
  BorrowNo: string;
  BorrowName: string;
  BorrowerId: number;
  BorrowDept: number;
  BorrowTypeId: number;
  BorrowTime: string;
  BorrowStatus: number;
  Remark: string;
  Details: AddToolBorrowDetailPayload[];
}

// 新增明细载荷类型
interface AddToolBorrowDetailPayload {
  ToolFixtureId: number;
  BorrowCount: number;
  StorageLocationId: number;
  ToolStatusWhenBorrow: number;
  Remark: string;
}

// 更新请求载荷类型
interface UpdateToolBorrowPayload {
  id: number;
  BorrowNo: string;
  BorrowName: string;
  BorrowerId: number;
  BorrowDept: number;
  BorrowTypeId: number;
  BorrowTime: string;
  BorrowStatus: number;
  Remark: string;
  Details: UpdateToolBorrowDetailPayload[];
}

// 更新明细载荷类型
interface UpdateToolBorrowDetailPayload {
  id: number;
  BorrowOrderId: number;
  ToolFixtureId: number;
  BorrowCount: number;
  StorageLocationId: number;
  ToolStatusWhenBorrow: number;
  Remark: string;
}

// 编码规则类型
interface CodingRule {
  id: number;
  targettablename?: string;
  rulename?: string;
}

const route = useRoute();
const router = useRouter();

const borrowerOptions = ref<UserOption[]>([]);
const departmentOptions = ref<DepartmentOption[]>([]);
const typeOptions = ref<BorrowTypeOption[]>([]);
const fixtureOptions = ref<FixtureOption[]>([]);
const seatOptions = ref<SelectOption[]>([]);
const toolStatusOptions = ref<SelectOption[]>([
  { label: "完好", value: 0 },
  { label: "需维修", value: 1 },
  { label: "待检修", value: 2 },
]);

const form = reactive<ToolBorrowForm>({
  id: 0,
  borrowNo: "",
  autoNo: false,
  borrowName: "",
  borrowerId: null,
  borrowerName: "",
  borrowDept: null,
  borrowDeptName: "",
  borrowTypeId: null,
  borrowTime: "",
  borrowStatus: 0,
  remark: "",
  details: [],
});

const saving = ref(false);
const selectedDetails = ref<DetailRow[]>([]);
const detailTotal = computed(() =>
  form.details.reduce((s, d) => s + Number(d.borrowCount || 0), 0)
);

const codingRuleId = ref<number | null>(null);
const lastGeneratedBorrowNo = ref("");
const manualBorrowNoBackup = ref("");
const buildUniqueCode = (prefix: string): string => {
  const timePart = Date.now().toString(36).toUpperCase();
  const randomPart = Math.floor(Math.random() * 1000)
    .toString()
    .padStart(3, "0");
  return `${prefix}${timePart}${randomPart}`;
};
const userDialogVisible = ref(false);
const userKeyword = ref("");
const userList = ref<UserDto[]>([]);
const userLoading = ref(false);
const filteredUsers = computed(() => {
  const keyword = userKeyword.value.trim().toLowerCase();
  if (!keyword) return userList.value;
  return userList.value.filter((item) =>
    ["username", "usernumber", "organname"]
      .map((key) => item[key as keyof UserDto]?.toString().toLowerCase() ?? "")
      .some((text) => text.includes(keyword))
  );
});

const getUserNameById = (id: number | null): string => {
  if (!id) return "";
  const hit = userList.value.find((x) => x.id === id);
  return hit?.username || "";
};

const fetchCodingRuleId = async (): Promise<void> => {
  try {
    const { data } = await https.Reads.get<ApiResult<CodingRule[]>>(
      "/CodingRule"
    );
    const list = data?.data || [];
    // 优先按目标表名，其次按名称关键字
    const hit =
      list.find(
        (x: CodingRule) => x.targettablename === "toolborrowheadermodel"
      ) ||
      list.find((x: CodingRule) =>
        String(x.rulename || "").includes("工具领用")
      ) ||
      list[0];
    codingRuleId.value = hit ? hit.id : null;
  } catch (e) {
    codingRuleId.value = null;
  }
};

const generateBorrowNo = async (): Promise<void> => {
  try {
    if (!codingRuleId.value) await fetchCodingRuleId();
    if (!codingRuleId.value) {
      // 后备：时间戳
      const fallback = buildUniqueCode("LY");
      form.borrowNo = fallback;
      lastGeneratedBorrowNo.value = fallback;
      return;
    }
    const res = await https.Writes.post<ApiResult<string>>(
      "/CodingRule/Generate",
      { ispreview: true },
      { params: { id: codingRuleId.value } }
    );
    const code = res?.data?.data;
    let finalCode = code || buildUniqueCode("LY");
    if (finalCode === lastGeneratedBorrowNo.value) {
      finalCode = buildUniqueCode("LY");
    }
    form.borrowNo = finalCode;
    lastGeneratedBorrowNo.value = finalCode;
  } catch (e) {
    const fallback = buildUniqueCode("LY");
    form.borrowNo = fallback;
    lastGeneratedBorrowNo.value = fallback;
  }
};

const handleAutoNoChange = async (v: boolean): Promise<void> => {
  if (v) {
    manualBorrowNoBackup.value = form.borrowNo || "";
    await generateBorrowNo();
  } else {
    if (form.borrowNo === lastGeneratedBorrowNo.value) {
      form.borrowNo = manualBorrowNoBackup.value || "";
    }
    manualBorrowNoBackup.value = form.borrowNo || "";
  }
};

const fetchUserList = async (): Promise<void> => {
  if (userLoading.value) return;
  userLoading.value = true;
  try {
    const res = await https.Reads.get<ApiPageing<UserDto>>("/RBAC/ShowUser", {
      params: { pageindex: 1, pagesize: 1000 },
    });
    const list = res.data?.data ?? [];
    userList.value = list;
    borrowerOptions.value = list.map((x: UserDto) => ({
      label: x.username,
      value: x.id,
    }));
  } finally {
    userLoading.value = false;
  }
};

const openUserDialog = (): void => {
  userDialogVisible.value = true;
  if (!userList.value.length) {
    fetchUserList();
  }
};

const handleAddDetail = (): void => {
  form.details.push({
    id: 0,
    toolFixtureId: null,
    toolFixtureName: "",
    borrowCount: 1,
    storageLocationId: null,
    storageLocationName: "",
    toolStatusWhenBorrow: null,
    remark: "",
  });
};

const removeDetailAt = (idx: number): void => {
  form.details.splice(idx, 1);
};

const handleUserPick = (row: UserDto): void => {
  form.borrowerId = row.id;
  form.borrowerName = row.username || "";
  form.borrowDept = row.organid ?? null;
  form.borrowDeptName = row.organname || "";
  userDialogVisible.value = false;
};

const handleDetailSelectionChange = (rows: DetailRow[]): void => {
  selectedDetails.value = rows;
};

const handleRemoveDetail = (): void => {
  if (!selectedDetails.value.length) {
    ElMessage.warning("请先选择明细");
    return;
  }
  form.details = form.details.filter((d) => !selectedDetails.value.includes(d));
};

const handleFixtureChange = (row: DetailRow, value: number | null): void => {
  const hit = fixtureOptions.value.find((x) => x.value === value);
  row.toolFixtureName = hit?.label || "";
  if (hit?.seatId && !row.storageLocationId) {
    row.storageLocationId = hit.seatId;
    row.storageLocationName = hit.seatName || "";
  }
};

const handleSeatChange = (row: DetailRow, value: number | null): void => {
  row.storageLocationId = value;
  const hit = seatOptions.value.find((x) => x.value === value);
  row.storageLocationName = hit?.label || "";
};

const refreshDetailLabels = (): void => {
  form.details.forEach((row) => {
    if (row.toolFixtureId) {
      const fixture = fixtureOptions.value.find(
        (x) => x.value === row.toolFixtureId
      );
      if (fixture) {
        row.toolFixtureName = fixture.label;
      }
    }
    if (row.storageLocationId) {
      const seat = seatOptions.value.find(
        (x) => x.value === row.storageLocationId
      );
      if (seat) {
        row.storageLocationName = seat.label;
      }
    }
  });
};

const fetchFixtureOptions = async (): Promise<void> => {
  try {
    const res = await https.Reads.get<ApiPageing<WorkFixtureDto>>(
      "/Applicae/work_fixturelist",
      { params: { Pageindex: 1, PageSize: 1000 } }
    );
    const list = res.data?.data ?? [];
    fixtureOptions.value = list.map((item) => ({
      label: item.work_fixturename,
      value: item.id,
      seatId: item.work_fixtureseatid,
      seatName: item.work_fixtureseatname,
    }));
    refreshDetailLabels();
  } catch {
    fixtureOptions.value = [];
  }
};

const fetchSeatOptions = async (): Promise<void> => {
  try {
    const res = await https.Reads.get<ApiPageing<WorkFixtureSeatDto>>(
      "/Applicae/Work_fixtureseatlist",
      { params: { Pageindex: 1, PageSize: 1000 } }
    );
    const list = res.data?.data ?? [];
    seatOptions.value = list.map((item) => ({
      label: item.work_fixtureseatname,
      value: item.id,
    }));
    refreshDetailLabels();
  } catch {
    seatOptions.value = [];
  }
};

const toAddPayload = (): AddToolBorrowPayload => ({
  BorrowNo: form.borrowNo,
  BorrowName: form.borrowName,
  BorrowerId: form.borrowerId || 0,
  BorrowDept: form.borrowDept || 0,
  BorrowTypeId: form.borrowTypeId || 0,
  BorrowTime: form.borrowTime || "",
  BorrowStatus: form.borrowStatus || 0,
  Remark: form.remark || "",
  Details: form.details.map((d) => ({
    ToolFixtureId: Number(d.toolFixtureId) || 0,
    BorrowCount: Number(d.borrowCount) || 0,
    StorageLocationId: Number(d.storageLocationId) || 0,
    ToolStatusWhenBorrow: Number(d.toolStatusWhenBorrow) || 0,
    Remark: d.remark || "",
  })),
});

const toUpdatePayload = (): UpdateToolBorrowPayload => ({
  id: form.id || 0,
  BorrowNo: form.borrowNo,
  BorrowName: form.borrowName,
  BorrowerId: form.borrowerId || 0,
  BorrowDept: form.borrowDept || 0,
  BorrowTypeId: form.borrowTypeId || 0,
  BorrowTime: form.borrowTime || "",
  BorrowStatus: form.borrowStatus || 0,
  Remark: form.remark || "",
  Details: form.details.map((d) => ({
    id: d.id || 0,
    BorrowOrderId: form.id || 0,
    ToolFixtureId: Number(d.toolFixtureId) || 0,
    BorrowCount: Number(d.borrowCount) || 0,
    StorageLocationId: Number(d.storageLocationId) || 0,
    ToolStatusWhenBorrow: Number(d.toolStatusWhenBorrow) || 0,
    Remark: d.remark || "",
  })),
});

const handleSubmit = async (): Promise<void> => {
  if (form.autoNo && !form.borrowNo) form.borrowNo = "LY" + Date.now();
  if (!form.borrowName) {
    ElMessage.error("请填写领用名称");
    return;
  }
  if (!form.details.length) {
    ElMessage.error("请至少添加一条领用明细");
    return;
  }
  try {
    saving.value = true;
    if (form.id && form.id > 0) {
      const res = await https.Writes.put<ApiResult<number>>(
        "/Appliance/ToolborrowdetailUpdate",
        toUpdatePayload()
      );
      if (res.data && res.data.code === 1) ElMessage.success("编辑成功");
      else ElMessage.success("编辑提交完成");
    } else {
      const res = await https.Writes.post<ApiResult<number>>(
        "/Appliance/ToolborrowdetailAdd",
        toAddPayload()
      );
      if (res.data && res.data.code === 1) ElMessage.success("新增成功");
      else ElMessage.success("新增提交完成");
    }
    router.push("/Toolborrowheaderlist");
  } catch (e) {
    ElMessage.error("保存失败，请稍后重试");
  } finally {
    saving.value = false;
  }
};

const handleCancel = (): void => {
  router.push("/Toolborrowheaderlist");
};

onMounted(async () => {
  const q = route.query;
  if (q && q.id) form.id = Number(q.id);

  // 预加载编码规则ID（用于自动编号）
  fetchCodingRuleId();
  fetchFixtureOptions();
  fetchSeatOptions();
  await fetchUserList();

  // 并行加载其他下拉选项
  const [deptRes, typeRes] = await Promise.allSettled([
    https.Reads.get<ApiPageing<OrganDto>>("/Organtion/ShowOrgan", {
      params: { pageindex: 1, pagesize: 1000 },
    }),
    https.Reads.get<ApiResult<BorrowTypeOption[]>>("/Applicae/Borrowtypelist"),
  ]);

  // 处理部门列表
  if (deptRes.status === "fulfilled") {
    const list = deptRes.value.data?.data ?? [];
    if (list.length > 0) {
      // 检查第一个元素的属性结构
      const firstItem = list[0] as any;
      console.log("部门数据结构示例:", firstItem);
      console.log("可用属性:", Object.keys(firstItem));
    }

    departmentOptions.value = list
      .map((x: any) => {
        // 尝试获取ID，支持Id、id、以及可能的其他变体
        const rawId = x.Id ?? x.id ?? x.ID;
        if (rawId === undefined || rawId === null) {
          console.warn(`部门数据缺少ID字段，部门名称: ${x.organname}`, x);
          return null;
        }
        const id = Number(rawId);
        // 确保ID是有效的数字
        if (isNaN(id) || id <= 0) {
          console.warn(`无效的部门ID: ${rawId}, 部门名称: ${x.organname}`);
          return null;
        }
        return {
          label: x.organname || "",
          value: id,
        };
      })
      .filter((opt): opt is DepartmentOption => opt !== null); // 过滤掉无效的选项

    console.log(`成功加载 ${departmentOptions.value.length} 个部门选项`);
    if (departmentOptions.value.length > 0) {
      console.log("部门选项示例:", departmentOptions.value.slice(0, 3));
    }
  } else {
    console.error("加载部门列表失败:", deptRes);
  }

  // 处理领用类型
  if (typeRes.status === "fulfilled") {
    const list = typeRes.value.data?.data ?? [];
    typeOptions.value = list;
  }

  // 编辑：获取详情并回填（含明细）
  // 确保在部门选项加载完成后再设置表单值，这样下拉框才能正确显示名称
  if (form.id && form.id > 0) {
    try {
      const res = await https.Reads.get<ApiResult<ToolBorrowHeaderDetailDto>>(
        "/Applicae/ToolborrowheaderDetail",
        { params: { id: form.id } }
      );
      const d = res.data?.data;
      if (!d) return;

      form.borrowNo = d.borrowNo;
      form.borrowName = d.borrowName;
      form.borrowerId = d.borrowerId;
      form.borrowerName = d.borrowerName || getUserNameById(d.borrowerId);

      // 处理部门字段：确保部门选项已加载，再设置部门ID
      const borrowDeptRaw = d.borrowDept;
      if (
        borrowDeptRaw !== null &&
        borrowDeptRaw !== undefined &&
        borrowDeptRaw !== ""
      ) {
        let deptId: number | undefined;
        if (typeof borrowDeptRaw === "string") {
          const trimmed = borrowDeptRaw.trim();
          if (trimmed !== "") {
            const parsed = Number(trimmed);
            deptId = Number.isNaN(parsed) ? undefined : parsed;
          }
        } else if (typeof borrowDeptRaw === "number") {
          deptId = borrowDeptRaw;
        }

        if (typeof deptId === "number" && !Number.isNaN(deptId) && deptId > 0) {
          const deptOption = departmentOptions.value.find(
            (opt) => Number(opt.value) === deptId
          );

          if (deptOption) {
            form.borrowDept = deptOption.value;
            form.borrowDeptName = deptOption.label;
          } else if (d.borrowDeptName) {
            const deptByName = departmentOptions.value.find(
              (opt) =>
                opt.label === d.borrowDeptName ||
                opt.label === String(d.borrowDeptName)
            );
            if (deptByName) {
              form.borrowDept = deptByName.value;
              form.borrowDeptName = deptByName.label;
            } else {
              form.borrowDept = null;
              console.warn(
                `未找到部门ID ${deptId} 或名称 "${d.borrowDeptName}" 对应的选项`
              );
            }
          } else {
            form.borrowDept = null;
            console.warn(
              `未找到部门ID ${deptId} 对应的选项，可用选项:`,
              departmentOptions.value.map((o) => `${o.value}:${o.label}`)
            );
          }
        } else if (d.borrowDeptName) {
          const deptByName = departmentOptions.value.find(
            (opt) =>
              opt.label === d.borrowDeptName ||
              opt.label === String(d.borrowDeptName)
          );
          form.borrowDept = deptByName ? deptByName.value : null;
          form.borrowDeptName = deptByName
            ? deptByName.label
            : d.borrowDeptName || "";
        } else {
          form.borrowDept = null;
          form.borrowDeptName = "";
        }
      } else {
        form.borrowDept = null;
        form.borrowDeptName = "";
      }
      if (!form.borrowDeptName && d.borrowDeptName) {
        form.borrowDeptName = d.borrowDeptName;
      }

      form.borrowTypeId = Number(d.borrowTypeId);

      // 使用nextTick确保Vue响应式更新完成，下拉框能正确显示名称
      await nextTick();

      // 将日期时间转换为字符串格式（YYYY-MM-DDTHH:mm:ss）
      if (typeof d.borrowTime === "string") {
        form.borrowTime = d.borrowTime;
      } else if (d.borrowTime instanceof Date) {
        const date = d.borrowTime;
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        form.borrowTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
      } else {
        form.borrowTime = "";
      }
      form.borrowStatus = d.borrowStatus;
      form.remark = d.remark || "";
      form.details = (d.details || []).map((x: ToolBorrowDetailItemDto) => ({
        id: x.id,
        toolFixtureId: x.toolFixtureId,
        toolFixtureName: x.toolFixtureName || "",
        borrowCount: x.borrowCount,
        storageLocationId: x.storageLocationId,
        storageLocationName: x.storageLocationName || "",
        toolStatusWhenBorrow: x.toolStatusWhenBorrow,
        remark: x.remark || "",
      }));
      refreshDetailLabels();
    } catch (e) {
      console.error("获取详情失败:", e);
    }
  } else {
    // 新增场景：若路由带有基础字段，则回填（可选）
    if (q && q.borrowNo) form.borrowNo = String(q.borrowNo);
    if (q && q.borrowName) form.borrowName = String(q.borrowName);
    if (q && q.borrowerId) {
      form.borrowerId = Number(q.borrowerId);
      form.borrowerName = getUserNameById(form.borrowerId);
    }
    if (q && q.borrowDept) {
      form.borrowDept = Number(q.borrowDept);
      const deptOption = departmentOptions.value.find(
        (opt) => Number(opt.value) === form.borrowDept
      );
      form.borrowDeptName = deptOption?.label || "";
    }
    if (q && q.borrowTypeId) form.borrowTypeId = Number(q.borrowTypeId);
    if (q && q.borrowTime) form.borrowTime = String(q.borrowTime);
    if (q && q.remark) form.remark = String(q.remark);
  }
});
</script>

<style scoped>
.tool-borrow-add {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  background: #f5f7fb;
  min-height: calc(100vh - 80px);
}

.page-hero {
  background: linear-gradient(135deg, #2d6aff, #5fa0ff);
  border-radius: 18px;
  padding: 24px;
  color: #fff;
  box-shadow: 0 15px 35px rgba(55, 120, 255, 0.25);
}

.hero-content {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  flex-wrap: wrap;
}

.hero-pretitle {
  margin: 0;
  font-size: 13px;
  letter-spacing: 1px;
  opacity: 0.9;
}

.hero-content h1 {
  margin: 4px 0;
  font-size: 26px;
  font-weight: 600;
}

.hero-desc {
  margin: 0;
  font-size: 14px;
  opacity: 0.85;
}

.hero-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.hero-tag {
  border-radius: 16px;
}

.hero-back {
  color: #fff;
  font-weight: 500;
}

.hero-stats {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 14px;
  padding: 16px;
  backdrop-filter: blur(6px);
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  text-transform: uppercase;
  opacity: 0.8;
}

.stat-value {
  font-size: 22px;
  font-weight: 600;
}

.stat-tip {
  font-size: 12px;
  opacity: 0.8;
}

.section-card {
  border-radius: 16px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.card-header p {
  margin: 2px 0 0;
  color: #909399;
  font-size: 13px;
}

.card-header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.card-hint {
  font-size: 13px;
  color: #606266;
}

.base-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.borrower-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.borrower-picker-btn {
  background: linear-gradient(135deg, #409eff, #36cfc9);
  border: none;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.35);
}

.borrower-picker-btn:focus,
.borrower-picker-btn:hover {
  background: linear-gradient(135deg, #36cfc9, #67c23a);
  box-shadow: 0 6px 15px rgba(54, 207, 201, 0.4);
}

.borrower-picker-btn :deep(.el-icon) {
  font-size: 18px;
}

.detail-toolbar {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 12px;
}

.toolbar-left {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.detail-table :deep(.el-table__header-wrapper th) {
  background: #f7f8fa;
  color: #303133;
  font-weight: 600;
}

.detail-table :deep(.el-select),
.detail-table :deep(.el-input),
.detail-table :deep(.el-input-number) {
  width: 100%;
}

.detail-summary {
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 13px;
  flex-wrap: wrap;
}

.page-actions {
  position: sticky;
  bottom: 0;
  background: rgba(245, 247, 251, 0.95);
  backdrop-filter: blur(8px);
  border-radius: 16px;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  box-shadow: 0 -8px 24px rgba(15, 23, 42, 0.08);
}

.actions-hint p {
  margin: 0;
  color: #606266;
  font-size: 13px;
}

.actions-buttons {
  display: flex;
  gap: 12px;
}

.manager-search {
  margin-bottom: 12px;
}

@media (max-width: 768px) {
  .hero-content {
    flex-direction: column;
  }

  .hero-actions {
    justify-content: flex-start;
  }

  .page-actions {
    flex-direction: column;
    align-items: flex-start;
  }

  .actions-buttons {
    width: 100%;
    justify-content: flex-end;
  }

  .actions-buttons .el-button {
    flex: 1;
  }
}
</style>
